import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import cookie from 'js-cookie'

// 创建axios实例
const service = axios.create({
    baseURL: '/dev-api',
    timeout: 15000 // 请求超时时间
})

// http request 拦截器
service.interceptors.request.use(
    config => {
        // 判断 cookie 中是否有值
        if (cookie.get('token')) {
            // 把值放到 cookie 中
            config.headers['token'] = cookie.get('token');
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);

// http response 拦截器
service.interceptors.response.use(
    response => {
        if(response.data.code === 208 || response.data.code === 229){
            // Message({
            //     message: '您还未登入，请先登入！',
            //     type: 'error',
            //     duration: 5 * 1000
            // })
            window.parent.$nuxt.$store.dispatch('user/updateLoginStatus', true)
            document.body.style.overflow = "hidden";
            return Promise.reject()
            // return Promise.resolve(new Error(response.data.message || 'Error'))
        }

        if(response.data.code === 231){
            Message({
                message: response.data.message,
                type: 'error',
                duration: 5 * 1000
            })
            cookie.remove("token")
            window.parent.$nuxt.$store.dispatch('user/updateLoginStatus', true)
            document.body.style.overflow = "hidden";
            return Promise.reject()
            // return Promise.resolve(new Error(response.data.message || 'Error'))
        }
        
        if (response.data.code !== 200) {
            Message({
                message: response.data.message,
                type: 'error',
                duration: 5 * 1000
            })
            return Promise.reject()
        } else {
            return response.data
        }
    },
    error => {
        return Promise.reject()
    })
export default service